/**
 * 数据表格require模块
 * @author 梁伟明
 */

define(['jquery', 'datatables.net', 'datatables.net-select'], function(){
	
	/**
	 * 处理选项
	 * @param {array} options
	 * @returns {array}
	 */
	function handle_options(options){
		if(options.action_column && options.action_column > 0){
			options.columnDefs.push({"targets" : options.action_column, "defaultContent" : ""});
		}
		//生成ajax对象
		if(!options.ajax && (options.form_id && options.url)){
			options.ajax = {
				"url": options.url,
				"type": "POST",
				"data" : function(data){
					//将form控件中的数据转换为json对象
					var json = $(options.form_id).serializeArray();
					$.each(json, function(i,field){
						data[field.name] = field.value;
					});
				}
			};
		}
		if(options.select_box){
			var select_box	= {"className": 'select-checkbox', "defaultContent": ""};
			options.select	= {"style": 'muti', "selector": 'td:first-child'};
			options.columns ? options.columns.unshift(select_box) : options.columns = [select_box];
		} else {
			options.select	= {"info" : false};
		}
		return options;		
	}
	
	return function(options){
		var defaults = {
			"dom" : 'irtlp',
			"buttons": [],
			//是否从服务端获取数据
			"serverSide": true,
			//ajax设置
			//"ajax" : {},
			//是否可排序
			"ordering" : false,
			//列设置
			"columnDefs" :[
				{
					"targets" : "_all",
					"searchable": false
				}
			],
			//配置每个列对应的数据键名
			"columns" :[],
			//这里读取语言文件会导致异步加载
			"language": {
				"url": "/static/plugins/datatables/language/chinese.json"
			},
			//是否显示checkbox
			"select_box" : true,
			"lengthMenu": [20, 40, 80, 100],
			"rowId" : 'id',
			'action_column' : 0,
			"inner_buttons_class" : "action-buttons"
			
		};
		$.extend(defaults, options);
		defaults = handle_options(defaults);
		
		var table = $(defaults.table_id).DataTable({
			"dom": defaults.dom,
			"buttons": defaults.buttons,			
			"serverSide": defaults.serverSide,			
			"ajax": defaults.ajax,
			"ordering": defaults.ordering,			
			"columnDefs": defaults.columnDefs,			
			"columns": defaults.columns,			
			"language": defaults.language,
			"rowId": defaults.rowId,
			"select": defaults.select,
			"lengthMenu": defaults.lengthMenu
		});

		//向服务器请求数据前的操作
		table.on('preXhr.dt', function (e, settings, data) {
			//删除列参数
			delete data.columns;

		});
		//表格获取数据后-重新画控制变量
		var xhr_draw = false;
		table.on('xhr.dt', function (e, settings, json, xhr) {
			xhr_draw = true;
		});
		
		if (defaults.action_column && defaults.action_buttons) {
			table.on('draw.dt', function (e, settings) {
				var len = table.column(0).data().length;
				if (xhr_draw) {
					//i是表格的行数
					for (i = 0; i < len; i++) {
						var cell = table.cell(i, defaults.action_column);
						//单元格网页对象
						var cell_element = cell.node();
						$.each(defaults.action_buttons, function (key, value) {
							var type = typeof(value);
							//如果是回调函数，则直接回调
							if(type == 'function'){
								var object = $(key); 
								value(object, i, table.row(i).id());
							//定义对象
							} else if(type == 'object'){
								var object = mk_buttons(value, i, table.row(i).id());		
								//按钮组回调函数
								if(value.callback){
									value.callback(object, i, table.row(i).id());
								}
							}    
							object.addClass(defaults.inner_buttons_class);
							object.appendTo(cell_element);
						});
					}
					xhr_draw = false;
				}
			});
		}

		if(defaults.select_box){
			/**
			 * 全选按钮
			 */
			$(".checkbox-selector").on('click', function () {
				var is_checked = $(this).attr('is_checked');
				if (is_checked == 1) {
					$(this).parent('tr').removeClass('selected');
					table.rows().deselect();
					$(this).attr("is_checked", 0);
				} else {
					$(this).parent('tr').addClass('selected');
					table.rows().select();
					$(this).attr("is_checked", 1);
				}
			});
		}

		/**
		 * 根据对象设置生成对应的按钮
		 * @returns {jquery html element}
		 */
		function mk_buttons(params, row_number, row_id){
			var type = params.type;
			if(type == 'action_group'){
				var container = $('<div class="btn-group"></div>');
				var ul = $('<ul class="dropdown-menu" role="menu"></ul>');
				$.each(params.buttons, function(key, value){
					//选项class
					var className = '';
					//选项id
					var id = '';
					//按钮对象本身
					var _this;
					if(value.className){
						className = value.className;
					}
					if(value.id){
						id = " id = '" + value.id + "'"; 
					}			
					if(key == 0){
						var button = $('<button type="button" class="btn btn-info '+ className + '" ' + id + '>'+ value.text + '</button>');
						$(button).appendTo(container);
						var drop = '\
						<button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown">\
							<span class="caret"></span>\
							<span class="sr-only">Toggle Dropdown</span>\
						</button>\
						';
						$(drop).appendTo(container);
						$(ul).appendTo(container);
						_this = button;
					} else {
						var li = $('<li class="'+ className + '" '+ id +'><a href="#">'+ value.text +'</a></li>');
						li.appendTo(ul);
						_this = li;
					}
					if(value.callback){
						value.callback(_this, row_number, row_id);
					}						
				});

			}
			return container;
		}
		
		/**
		 * 获取选中的id
		 * @returns {Array}
		 */
		table.get_selected_ids = function(){
			var selected = table.rows(".selected").ids();
			var result = [];
			$.each(selected, function (key, value) {
				result.push(value);
			});
			return result;
		};
		
		/**
		 * 重新获取数据
		 */
		table.search = function(){
			table.ajax.reload();
		};
		
		return table;
	};
});